package com.demo.apparel.controller.uniapp;

import cn.hutool.json.JSONUtil;
import com.demo.apparel.common.Result;
import com.demo.apparel.dto.uniapp.GoodsCreateDTO;
import com.demo.apparel.dto.uniapp.GoodsPageQueryDTO;
import com.demo.apparel.dto.uniapp.GoodsUploadDTO;
import com.demo.apparel.dto.uniapp.GoodsWithAvatarDTO;
import com.demo.apparel.entity.Goods;
import com.demo.apparel.entity.Match;
import com.demo.apparel.service.uniapp.WxGoodsService;
import com.demo.apparel.vo.PageVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/wx/goods")
@Tag(name = "衣物挂售卖商品接口", description = "挂售卖商品信息")
public class WxGoodsController {

    @Autowired
    private WxGoodsService wxGoodsService;

    @PostMapping("/create")
    @Operation(summary = "挂售衣物")
    public Result<Void> createGoods(@RequestBody GoodsUploadDTO dto,
                                    @RequestAttribute("userId") String userId) throws JsonProcessingException {
        wxGoodsService.createGoods(dto, userId);
        return Result.success();
    }
    @PostMapping("/list")
    @Operation(summary = "获取商品列表分页（支持name模糊查询）")
    public Result<PageVO<Map<String, Object>>> listGoods(@RequestBody GoodsPageQueryDTO queryDTO) {
        // 调用服务层获取商品分页数据
        PageVO<GoodsWithAvatarDTO> page = wxGoodsService.getGoodsPage(
                queryDTO.getPageNum(),
                queryDTO.getPageSize(),
                queryDTO.getName(),
                queryDTO.getCategory()

        );
        // 将 GoodsWithAvatarDTO 转换为 Map<String, Object>，便于前端处理
        List<Map<String, Object>> records = new ArrayList<>();
        for (GoodsWithAvatarDTO goods : page.getRecords()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", goods.getId());
            map.put("clothesId", goods.getClothesId());
            map.put("userId", goods.getUserId());
            map.put("category", goods.getCategory());
            map.put("name", goods.getName());
            map.put("price", goods.getPrice());
            map.put("description", goods.getDescription());
            map.put("introduce", goods.getIntroduce());
            map.put("size", goods.getSize());
            map.put("season", goods.getSeason());
            map.put("statusSale", goods.getStatusSale());
            map.put("userAvatar", goods.getUserAvatar());
            map.put("imageUrls", JSONUtil.toList(goods.getImageUrls(), String.class));
            map.put("createdTime", goods.getCreatedTime());
            map.put("updatedTime", goods.getUpdatedTime());

            records.add(map);
        }

        // 创建分页结果对象
        PageVO<Map<String, Object>> resultPage = new PageVO<>(records, page.getTotal(), page.getPageNum(), page.getPageSize());

        return Result.success(resultPage);
    }

    @PostMapping(value = "/uploadImageUrls", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传搭配图片")
    public Result<List<String>> uploadImages(@RequestParam("files") List<MultipartFile> files) throws IOException {
        if (files == null || files.isEmpty()) {
            return (Result<List<String>>) Result.error("500","错误");
        }

        String uploadDir = System.getProperty("user.dir") + "/goods/image/";
        String urlPrefix = "/static/goods/image/";
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        List<String> resultList = new ArrayList<>();
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename != null && originalFilename.contains(".")
                    ? originalFilename.substring(originalFilename.lastIndexOf("."))
                    : "";
            String filename = UUID.randomUUID().toString().replace("-", "") + suffix;
            String imageUrl = urlPrefix + filename;

            file.transferTo(new File(dir, filename));
            resultList.add(imageUrl);
        }

        return Result.success(resultList);
    }

    @GetMapping
    @Operation(summary = "根据商品ID获取商品详情")
    public Result<GoodsCreateDTO> getGoodsDetail(@RequestParam("id") String id) {
        GoodsCreateDTO goodsDetail = wxGoodsService.getGoodsDetailById(id);
        return Result.success(goodsDetail);
    }


}
